package com.example.fragmentdemo.player;

import static androidx.constraintlayout.helper.widget.MotionEffect.TAG;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.example.fragmentdemo.R;
import com.example.fragmentdemo.constant.Constant;

import java.io.File;

public class MusicPlayerActivity extends AppCompatActivity {
    private MediaPlayer mediaPlayer;
    private Uri fileUri;
    private String musicUrl;
    private String filename;
    private String time;
    private Button playButton;
    private SeekBar start,end;
    private TextView startText,endText,title;
    private MediaPlayer song;
    private ImageView imageView,love;
    private Animation animation;
    private int songTotalTime;

    private int loveFlag=0;
    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_player);

        playButton=findViewById(R.id.play);
        startText=findViewById(R.id.TextStart);
        endText=findViewById(R.id.TextEnd);
        title=findViewById(R.id.title);
        imageView=findViewById(R.id.img);
        love=findViewById(R.id.love);
        animation= AnimationUtils.loadAnimation(this,R.anim.rotation);

        musicUrl = getIntent().getStringExtra("uri");
        filename = getIntent().getStringExtra("name");
        time = getIntent().getStringExtra("time");

        title.setText(filename);

        assert musicUrl != null;
        fileUri = Uri.fromFile(new File(musicUrl));
        Log.d(TAG, "musicUrl: "+fileUri+"   "+filename+"   "+time);
        song=MediaPlayer.create(this,fileUri);
        song.setLooping(true);
        song.seekTo(0);
        song.setVolume(0.8f,0.8f);
        songTotalTime=song.getDuration();

        start=findViewById(R.id.PlayLine);
        start.setMax(songTotalTime);
        start.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser){
                    song.seekTo(progress);
                    start.setProgress(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        end=findViewById(R.id.volume);
        end.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                float volume=progress/100f;
                song.setVolume(volume,volume);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (song!=null){
                    try {
                        Message message=new Message();
                        message.what=song.getCurrentPosition();
                        handler.sendMessage(message);
                        Thread.sleep(1000);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
    @SuppressLint("HandlerLeak")
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            int seekBarPosition=msg.what;

            start.setProgress(seekBarPosition);

            String time=createTimeText(seekBarPosition);
            startText.setText(time);

            String remainTime=createTimeText(songTotalTime-seekBarPosition);
            endText.setText("-"+remainTime);

        }
    };

    public String createTimeText(int time){
        String timeText;
        int min=time/1000/60;
        int sec=time/1000%60;
        timeText=min+":";
        if(sec<0){
            timeText+="0";

        }
        timeText+=sec;
        return timeText;
    }



    public void PlayButton(View view) {
        if (!song.isPlaying()){
            song.start();
            imageView.startAnimation(animation);
            playButton.setBackgroundResource(R.drawable.baseline_pause_24);
        }else {
            song.pause();
            imageView.clearAnimation();
            playButton.setBackgroundResource(R.drawable.baseline_play_arrow_24);
        }
    }
    public void love(View view){
        if (loveFlag==0){
            love.setImageResource(R.drawable.baseline_favorite_24);
            loveFlag=1;
        }else {
            love.setImageResource(R.drawable.baseline_favorite_border_24);
            loveFlag=0;
        }
    }
    public void share(View view){
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        File file = new File(musicUrl);
        Uri contentUri = FileProvider.getUriForFile(this, Constant.AUTHORITY, file);
        shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
        shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivity(shareIntent);
    }
}